package com.mlizhi.modules.login;

import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mlizhi.base.MlzApplication;
import com.mlizhi.base.NetWorkManager;
import com.mlizhi.base.SecurityUtil;
import com.mlizhi.base.Session;
import com.mlizhi.kingdom.R;
import com.mlizhi.modules.spec.util.JsonUtil;
import com.mlizhi.utils.Constants;
import com.mlizhi.utils.Utils;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;

/**
 * handset devices, settings are presented as a single list. On tablets,
 * settings are split by category, with category headers shown to the left of
 * the list of settings.
 * <p>
 * See <a href="http://developer.android.com/design/patterns/settings.html">
 * Android Design: Settings</a> for design guidelines and the <a
 * href="http://developer.android.com/guide/topics/ui/settings.html">Settings
 * API Guide</a> for more information on developing a Settings UI.
 */
public class Regist1Activity extends Activity {

	private Session mSession;
	private MlzApplication mlzApplication;
	private EditText phoneNoEditText,validCodeEditText;
	private RequestQueue mRequestQueue;
	private Context mContext;
	private String phoneNumberInput = "";
	private TextView validCodeBtn = null;
	
	private String codeInput ="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_login_regist1);
		mlzApplication = (MlzApplication) getApplication();
		mlzApplication.addActivity(this);
		mSession = Session.get(getApplicationContext());
		/** 发送策略定义了用户由统计分析SDK产生的数据发送回友盟服务器的频率。 */
		MobclickAgent.updateOnlineConfig( mContext );
		/** 设置是否对日志信息进行加密, 默认false(不加密). */
		AnalyticsConfig.enableEncrypt(true);
		phoneNoEditText = (EditText) findViewById(R.id.user_info_phone_number);
		validCodeEditText = (EditText) findViewById(R.id.user_valid_code_edit);
		validCodeBtn = (TextView) findViewById(R.id.user_valid_code_btn);
		
		
	}

	public void onRegist1Click(View view) {
		switch (view.getId()) {
		case R.id.regist1_password_back:
			finish();
			break;
		case R.id.user_valid_code_btn:
			phoneNumberInput = phoneNoEditText.getText().toString();
//			getValidCode();
			checkMobileExist();
			break;
		case R.id.id_regist1_next:
			checkCode();
			break;

		default:
			break;
		}
	}
	
	
	
	

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			String second = "";
			
			switch (msg.what) {
			case 0:
				validCodeBtn.setClickable(false);
				break;
				
			case 1:
				second = (String) msg.obj;
//				validCodeBtn.setText("剩余"+second+"秒");
				validCodeBtn.setText(Html.fromHtml("剩余<font color=gray>(<big>"+second+"</big>)</font>秒"));
				break;
			
			case 2:
				validCodeBtn.setClickable(true);
				validCodeBtn.setText(R.string.get_valid_code);
				break;
			default:
				break;
			}
			
		}
		
	};
	
	//验证手机号码是否已经注册
	private void checkMobileExist() {
		if (!"".equals(phoneNumberInput) && phoneNumberInput != null) {
			if(!Utils.matchPhoneNumber(phoneNumberInput)){
				Toast.makeText(mContext, "请输入手机号！", Toast.LENGTH_SHORT).show();
				return ;
			}
			boolean netUsable = NetWorkManager.getNewInstance().isNetworkConnected(mContext);
			if (netUsable) {
				mRequestQueue = Volley.newRequestQueue(getApplicationContext());
				// Request a string response from the provided URL.
				StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_CHECK_MOBILE_URL,
						new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						String code = JsonUtil.getHeaderCode(response);
						if (Constants.RESULT_JSON_HEADER_CODE_SUCCESS.equals(code)) {
							getValidCode();
						} else {
							Toast.makeText(mContext,"该手机号码已注册！",Toast.LENGTH_SHORT).show();
						}
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Toast.makeText(mContext, error.getMessage(),Toast.LENGTH_SHORT).show();
					}
				}) {
					
					@Override
					protected Map<String, String> getParams() throws AuthFailureError {
						
						String timestamp = SecurityUtil.getTimestamp();
						Map<String, String> params = new HashMap<String, String>();
						params.put("companyId", Constants.COMPANY_ID);
						params.put("mobile", phoneNumberInput);
						params.put(Constants.URL_TIMESTAMP, timestamp);
						params.put(Constants.URL_KEY,SecurityUtil.getMd5String(timestamp));
						return params;
					}
				};
				// stringRequest.setTag(TAG);
				mRequestQueue.add(stringRequest);
				mRequestQueue.start();
			} else {
				Toast.makeText(mContext, R.string.net_connected_failure,Toast.LENGTH_SHORT).show();
			}
			
		} else {
			Toast.makeText(mContext, "手机号码不能为空！",Toast.LENGTH_SHORT).show();
		}
	}
	
	
	/**
	 * 获取验证码
	 */
	private void getValidCode() {
		if (!"".equals(phoneNumberInput) && phoneNumberInput != null) {
			if(!Utils.matchPhoneNumber(phoneNumberInput)){
				Toast.makeText(mContext, "请输入手机号！", Toast.LENGTH_SHORT).show();
				return ;
			}
			boolean netUsable = NetWorkManager.getNewInstance().isNetworkConnected(mContext);
			if (netUsable) {
				mRequestQueue = Volley.newRequestQueue(getApplicationContext());
				// Request a string response from the provided URL.
				StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_POST_GET_VALID_CODE,
						new Response.Listener<String>() {
							@Override
							public void onResponse(String response) {
								String code = JsonUtil.getHeaderCode(response);
								if (Constants.RESULT_JSON_HEADER_CODE_SUCCESS.equals(code)) {
									Message msg = mHandler.obtainMessage();
									msg.what = 0;
									mHandler.sendMessage(msg);
									
									new Thread() {
										int second = 75;
										
										@Override
										public void run() {
											while (second > 0) {
												Message msg = mHandler.obtainMessage();
												msg.what = 1;
												msg.obj = String.valueOf(second--);
												mHandler.sendMessage(msg);
												try {
													Thread.sleep(1000);
												} catch (InterruptedException e) {
													// TODO Auto-generated catch block
													e.printStackTrace();
												}
											}
											Message msg = mHandler.obtainMessage();
											msg.what = 2;
											mHandler.sendMessage(msg);
											
										}
									}.start();
								} else {
									Toast.makeText(mContext,JsonUtil.getHeaderErrorInfo(response),Toast.LENGTH_SHORT).show();
								}
							}
						}, new Response.ErrorListener() {
							@Override
							public void onErrorResponse(VolleyError error) {
								Toast.makeText(mContext, error.getMessage(),Toast.LENGTH_SHORT).show();
							}
						}) {
					
					@Override
					protected Map<String, String> getParams() throws AuthFailureError {

						String timestamp = SecurityUtil.getTimestamp();
						Map<String, String> params = new HashMap<String, String>();
						params.put("companyId", Constants.COMPANY_ID);
						params.put("mobile", phoneNumberInput);
						params.put(Constants.URL_TIMESTAMP, timestamp);
						params.put(Constants.URL_KEY,SecurityUtil.getMd5String(timestamp));
						return params;
					}
				};
				// stringRequest.setTag(TAG);
				mRequestQueue.add(stringRequest);
				mRequestQueue.start();
			} else {
				Toast.makeText(mContext, R.string.net_connected_failure,Toast.LENGTH_SHORT).show();
			}

		} else {
			Toast.makeText(mContext, "手机号码不能为空！！",Toast.LENGTH_SHORT).show();
		}
	}
	
	/**
	 * 验证码检测
	 */
	private void checkCode() {
		if ("".equals(phoneNumberInput) || phoneNumberInput == null) {
			Toast.makeText(mContext, "手机号码不能为空！！",Toast.LENGTH_SHORT).show();
		}
		codeInput = validCodeEditText.getText().toString();
		if (!"".equals(codeInput) && codeInput != null) {
			boolean netUsable = NetWorkManager.getNewInstance() .isNetworkConnected(mContext);
			if (netUsable) {
				mRequestQueue = Volley.newRequestQueue(getApplicationContext());
				// Request a string response from the provided URL.
				StringRequest stringRequest = new StringRequest(
						Request.Method.POST, Constants.URL_POST_CHECK_CODE,
						new Response.Listener<String>() {
							@Override
							public void onResponse(String response) {
								String code = JsonUtil.getHeaderCode(response);
								if (Constants.RESULT_JSON_HEADER_CODE_SUCCESS .equals(code)) {
									mSession.setAccount(phoneNumberInput);
									Regist1Activity.this .startActivity(new Intent( Regist1Activity.this, Regist2Activity.class));
								} else {
									Toast.makeText( mContext, JsonUtil.getHeaderErrorInfo(response), Toast.LENGTH_SHORT).show();
								}
							}
						}, new Response.ErrorListener() {
							@Override
							public void onErrorResponse(VolleyError error) {
								Toast.makeText(mContext, error.getMessage(), Toast.LENGTH_SHORT).show();
							}
						}) {
					@Override
					protected Map<String, String> getParams() throws AuthFailureError {

						String timestamp = SecurityUtil.getTimestamp();
						Map<String, String> params = new HashMap<String, String>();
						params.put("mobile", phoneNumberInput);
						params.put("sms", codeInput);
						params.put("companyId", Constants.COMPANY_ID);
						params.put(Constants.URL_TIMESTAMP, timestamp);
						params.put(Constants.URL_KEY,
								SecurityUtil.getMd5String(timestamp));
						return params;
					}
				};
				// stringRequest.setTag(TAG);
				mRequestQueue.add(stringRequest);
				mRequestQueue.start();
			} else {
				Toast.makeText(mContext, R.string.net_connected_failure,
						Toast.LENGTH_SHORT).show();
			}

		}else{
			Toast.makeText(mContext, "请输入验证码！",
					Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("SplashScreen"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
	    MobclickAgent.onResume(this);          //统计时长
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("SplashScreen"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息 
		MobclickAgent.onPause(this);
	}

}